﻿using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

namespace Tools.Helper
{
    public class Google
    {
        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/calendar-dotnet-quickstart.json

        public CalendarService Service { get; set; }

        #region 获取事件

        public Google()
        {
            string[] Scopes = { CalendarService.Scope.Calendar };
            string ApplicationName = "Google Calendar API .NET Quickstart";
            UserCredential credential;

            using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result;
                //Console.WriteLine("凭证文件保存到: " + credPath);
            }

            //创建谷歌日历API服务。
            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });
            this.Service = service;
        }

        //public string GetEvents(DateTime time, out string timeStr)
        //{
        //    timeStr = DateTime.Now.ToString("HH:mm");
        //    //定义请求参数。
        //    EventsResource.ListRequest request = this.Service.Events.List("primary");
        //    request.TimeMin = Convert.ToDateTime(time.ToShortDateString());
        //    request.TimeMax = Convert.ToDateTime(time.AddDays(1).ToShortDateString());
        //    request.ShowDeleted = false;
        //    request.SingleEvents = true;
        //    //request.MaxResults = 1000;
        //    request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;

        //    //列出事件。
        //    var str = new StringBuilder();
        //    Events events = request.Execute();

        //    var dic = new Dictionary<string, bool>()
        //    {
        //        {"上午",true },
        //        {"下午",true },
        //        {"明日计划",true },
        //        {"晚上",true }
        //    };

        //    if (events.Items != null && events.Items.Count > 0)
        //    {
        //        var items = events.Items.OrderBy(ex => ex.Start.DateTime).ThenBy(ex => ex.Summary);
        //        foreach (var item in items)
        //        {
        //            var nr = item.Summary;
        //            if (item.Start.DateTime != null)
        //            {
        //                var start = item.Start.DateTime.Value.ToString("HH:mm");
        //                var end = item.End.DateTime.Value.ToString("HH:mm");
        //                timeStr = end;

        //                var timeName = TimeName(dic, start, end);
        //                if (!string.IsNullOrEmpty(timeName))
        //                {
        //                    str.Append(timeName + "\r\n");
        //                }
        //                var haoshi = (item.End.DateTime.Value - item.Start.DateTime.Value).TotalHours;
        //                var hs = "";
        //                if (haoshi >= 1)
        //                {
        //                    hs = haoshi + "小时";
        //                }
        //                else
        //                {
        //                    hs = (haoshi * 60) + "分钟";
        //                }
        //                if (start == end)//明日计划
        //                {
        //                    nr = item.Summary;
        //                }
        //                else
        //                {
        //                    nr = string.Format("[{0}-{1} {2}]:{3}", start, end, hs, item.Summary);
        //                }
        //            }
        //            str.Append(nr + "\r\n");
        //        }
        //    }
        //    else
        //    {
        //        str.Append("没有发现事件。");
        //    }

        //    return str.ToString();
        //}

        ///// <summary>
        ///// 设置时间名称
        ///// </summary>
        ///// <param name="dic"></param>
        ///// <param name="start"></param>
        ///// <returns></returns>
        //private string TimeName(Dictionary<string, bool> dic, string start, string end)
        //{
        //    var result = "";
        //    if (dic["明日计划"] && start == "17:30" && end == "17:30")
        //    {
        //        dic["明日计划"] = false;
        //        result = "明日计划";
        //    }
        //    else if (dic["上午"] && Convert.ToDateTime("2018-01-01 " + start) >= Convert.ToDateTime("2018-01-01") && Convert.ToDateTime("2018-01-01 " + start) < Convert.ToDateTime("2018-01-01 12:00"))
        //    {
        //        dic["上午"] = false;
        //        result = "上午";
        //    }
        //    else if (dic["下午"] && Convert.ToDateTime("2018-01-01 " + start) >= Convert.ToDateTime("2018-01-01 12:00") && Convert.ToDateTime("2018-01-01 " + start) < Convert.ToDateTime("2018-01-01 18:00"))
        //    {
        //        dic["下午"] = false;
        //        result = "下午";
        //    }
        //    else if (dic["晚上"] && Convert.ToDateTime("2018-01-01 " + start) >= Convert.ToDateTime("2018-01-01 18:00"))
        //    {
        //        dic["晚上"] = false;
        //        result = "晚上";
        //    }
        //    return result;
        //}
        #endregion

        #region 添加事件

        ///// <summary>
        ///// 添加
        ///// </summary>
        ///// <param name="Title">标题</param>
        ///// <param name="Location"></param>
        ///// <param name="StartTime"></param>
        ///// <param name="EndTime"></param>
        //public string Add(string Title, string Location, string StartTime, string EndTime)
        //{
        //    // Refer to the .NET quickstart on how to setup the environment:
        //    // https://developers.google.com/calendar/quickstart/dotnet
        //    // Change the scope to CalendarService.Scope.Calendar and delete any stored
        //    // credentials.
        //    Event newEvent = new Event()
        //    {
        //        Summary = Title,
        //        Location = Location,
        //        //Description = "A chance to hear more about Google's developer products.",

        //        Start = new EventDateTime()
        //        {
        //            DateTime = DateTime.Parse(StartTime),
        //            //Date = StartTime
        //        },
        //        End = new EventDateTime()
        //        {
        //            DateTime = DateTime.Parse(EndTime),
        //            //Date = EndTime
        //        },
        //        //Recurrence = new String[] { "RRULE:FREQ=DAILY;COUNT=2" },
        //        //Attendees = new EventAttendee[]
        //        //            {
        //        //                new EventAttendee() { Email = "lpage@example.com" },
        //        //                new EventAttendee() { Email = "sbrin@example.com" },
        //        //            },
        //        //Reminders = new Event.RemindersData()
        //        //{
        //        //    UseDefault = false,
        //        //    Overrides = new EventReminder[]
        //        //                            {
        //        //                                new EventReminder() { Method = "email", Minutes = 24 * 60 },
        //        //                                new EventReminder() { Method = "sms", Minutes = 10 },
        //        //                            }
        //        //}
        //    };

        //    String calendarId = "primary";
        //    EventsResource.InsertRequest request = this.Service.Events.Insert(newEvent, calendarId);
        //    Event createdEvent = request.Execute();
        //    return "成功";
        //}

        #endregion
    }
}
